package com.qinglei.recoup.system.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.qinglei.recoup.common.domain.CommonRes;
import com.qinglei.recoup.common.domain.Tree;
import com.qinglei.recoup.common.exception.RedisConnectException;
import com.qinglei.recoup.common.tenant.TenantContextHolder;
import com.qinglei.recoup.common.utils.JsonUtils;
import com.qinglei.recoup.common.utils.RecoupUtil;
import com.qinglei.recoup.hmp.service.HmpDeviceService;
import com.qinglei.recoup.system.domain.Bed;
import com.qinglei.recoup.system.domain.Radar;
import com.qinglei.recoup.system.domain.RadarBed;
import com.qinglei.recoup.system.domain.SystemConfig;
import com.qinglei.recoup.system.pojo.*;
import com.qinglei.recoup.system.service.RadarBedService;
import com.qinglei.recoup.system.service.RadarService;
import com.qinglei.recoup.system.service.SystemConfigService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zxy
 */

@Api(tags = "监测仪相关控制器")
@Validated
@RestController
@RequestMapping("/radar")
public class RadarController {

    @Autowired
    private RadarService radarService;

    @Autowired
    private RadarBedService radarBedService;

    @Autowired
    private SystemConfigService systemConfigService;

    @Autowired
    private HmpDeviceService hmpDeviceService;


    /*@ApiOperation(value = "查询监测仪")
    @GetMapping("/showList")
    public CommonRes<List<RadarShowVO>> getRadarShowList() {
        List<RadarShowVO> radarShowVOS = new ArrayList<>();
        List<Radar> radars = radarService.getBaseMapper().selectList(null);
        RadarShowVO radarShowVO = new RadarShowVO();
        for (Radar rsv:radars) {
            BeanUtils.copyProperties(rsv,radarShowVO);
            radarShowVOS.add(radarShowVO);
        }
        return CommonRes.ok(radarShowVOS);
    }*/

    @ApiOperation(value = "分页查询监测仪")
    @GetMapping("/showPage")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页码，从1开始，默认是1", paramType = "query", dataType = "Integer", required = false),
            @ApiImplicitParam(name = "pageSize", value = "每页条数，默认20", paramType = "query", dataType = "Integer")
    })
    public CommonRes<RadarBedPageVO> showPageRadar(PageParam pageParam) {
        RadarSearchParam radarSearchParam = new RadarSearchParam();
        BeanUtils.copyProperties(pageParam, radarSearchParam);
        RadarBedPageVO radarBedPageVO = radarService.showPageRadar(radarSearchParam);
        return CommonRes.ok(radarBedPageVO);
    }

    @ApiOperation(value = "添加监测仪")
    @PostMapping
    public CommonRes addRadar(@Valid @RequestBody AddRadarParam addRadarParam) {
        Integer tenantId = TenantContextHolder.getTenantId();
        TenantContextHolder.clear();
        Integer integer = radarService.getBaseMapper().selectCount(Wrappers.<Radar>lambdaQuery().eq(Radar::getSnCode, addRadarParam.getSnCode()));
        if (integer > 0) {
            return CommonRes.failed("当前监测仪名称已存在");
        }
        TenantContextHolder.setTenantId(tenantId);
        Radar radar = new Radar();
        BeanUtils.copyProperties(addRadarParam, radar);
        boolean save = radarService.save(radar);
        if (save) {
            return CommonRes.ok();
        }
        return CommonRes.failed("新增监测仪失败");
    }


    @ApiOperation(value = "通过id查询监测仪")
    @GetMapping("/{id}")
    @ApiImplicitParam(name = "id", value = "id", paramType = "path", dataType = "Integer", required = true)
    public CommonRes<RadarVO> getRadarById(@PathVariable Integer id) {
        Radar radar = radarService.getBaseMapper().selectById(id);
        RadarVO radarVO = new RadarVO();
        BeanUtils.copyProperties(radar, radarVO);
        return CommonRes.ok(radarVO);
    }


    /*@ApiOperation(value = "修改监测仪")
    @PutMapping
    @ApiImplicitParams({
            @ApiImplicitParam(name = "id", value = "id", paramType = "body", dataType = "Integer",required = true),
            @ApiImplicitParam(name = "snCode", value = "监测仪设备SN码", paramType = "body", dataType = "String",required = true)
    })
    public CommonRes<RadarVO> getRadarById(@RequestBody RadarVO radarVO) {
        Radar radar = new Radar();
        BeanUtils.copyProperties(radarVO,radar);
        int count = radarService.getBaseMapper().updateById(radar);
        if (count>0){
            return CommonRes.ok("修改成功");
        }
        return CommonRes.failed("修改失败");
    }*/

    @ApiOperation(value = "绑定床位与监测仪")
    @PostMapping("/radarBed")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "radarId", value = "监测仪ID", paramType = "body", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "bedId", value = "床位ID", paramType = "body", dataType = "Integer", required = true)
    })
    public CommonRes<RadarVO> addRadarBed(@Valid @RequestBody RadarBedParam radarBedParam) {
        RadarBed radarBed1 = radarBedService.getBaseMapper().selectOne(Wrappers.<RadarBed>lambdaQuery().eq(RadarBed::getRadarId, radarBedParam.getRadarId()));
        if (radarBed1 != null) {
            radarBed1.setBedId(radarBedParam.getBedId());
            boolean flag = radarBedService.updateById(radarBed1);
            if (flag) {
                return CommonRes.ok("绑定成功");
            }
        } else {
            RadarBed radarBed = new RadarBed();
            BeanUtils.copyProperties(radarBedParam, radarBed);
            int count = radarBedService.getBaseMapper().insert(radarBed);
            if (count > 0) {
                return CommonRes.ok("绑定成功");
            }
        }
        return CommonRes.failed("绑定失败");
    }

    @ApiOperation(value = "解除绑定床位与监测仪")
    @DeleteMapping("/radarBed")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "radarId", value = "监测仪ID", paramType = "body", dataType = "Integer", required = true),
            @ApiImplicitParam(name = "bedId", value = "床位ID", paramType = "body", dataType = "Integer", required = true)
    })
    public CommonRes<RadarVO> delRadarBedById(@Valid @RequestBody RadarBedParam radarBedParam) {
        int count = radarBedService.getBaseMapper().delete(Wrappers.<RadarBed>lambdaUpdate()
                .eq(RadarBed::getBedId, radarBedParam.getBedId())
                .eq(RadarBed::getRadarId, radarBedParam.getRadarId()));
        if (count > 0) {
            return CommonRes.ok("解除绑定成功");
        }
        return CommonRes.failed("解除绑定失败");
    }

    @ApiOperation(value = "添加监测仪默认检测时间")
    @PostMapping("/MonitorTime")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "startTime", value = "开始时间", paramType = "body", dataType = "String", required = true),
            @ApiImplicitParam(name = "endTime", value = "结束时间", paramType = "body", dataType = "String", required = true)
    })
    public CommonRes addRadarMonitorTime(@Valid @RequestBody TimePeriodParam monitorTimeQO) {
        //查询要录入的时间段是否与已存在的时间段有重叠时间段
        boolean flag = systemConfigService.overlap(monitorTimeQO, SystemConfigService.TYPE_DEF_MONITOR_TIME);
        if (flag) {
            return CommonRes.failed("录入时间与已存在的巡视时间有重叠段");
        }
        String json = JsonUtils.objectToJson(monitorTimeQO);
        SystemConfig systemConfig = new SystemConfig();
        systemConfig.setValue(json);
        systemConfig.setType(SystemConfigService.TYPE_DEF_MONITOR_TIME);
        int count = systemConfigService.getBaseMapper().insert(systemConfig);
        if (count > 0) {
            return CommonRes.ok("添加监测仪默认检测时间成功");
        }
        return CommonRes.failed("添加监测仪默认检测时间失败");
    }

    @ApiOperation(value = "查询监测仪默认检测时间")
    @GetMapping("/MonitorTime")
    public CommonRes<List<MonitorTimeVO>> getRadarMonitorTime() {
        List<MonitorTimeVO> monitorTimeVOS = new ArrayList<>();
        List<SystemConfig> systemConfigs = systemConfigService.getBaseMapper().selectList(Wrappers.<SystemConfig>lambdaQuery().eq(SystemConfig::getType, SystemConfigService.TYPE_DEF_MONITOR_TIME));
        for (SystemConfig sc : systemConfigs) {
            MonitorTimeVO monitorTimeVO = JsonUtils.jsonToBean(sc.getValue(), MonitorTimeVO.class);
            monitorTimeVO.setId(sc.getId());
            monitorTimeVOS.add(monitorTimeVO);
        }
        return CommonRes.ok(monitorTimeVOS);
    }

    @ApiOperation(value = "删除监测仪默认检测时间")
    @DeleteMapping("/MonitorTime/{id}")
    public CommonRes delRadarMonitorTime(@PathVariable Integer id) {
        int count = systemConfigService.getBaseMapper().deleteById(id);
        if (count > 0) {
            return CommonRes.ok();
        }
        return CommonRes.failed("删除监测仪默认检测时间失败");
    }

    @ApiOperation(value = "修改离床到异常时间阈值")
    @PutMapping("/abnormalTime")
    public CommonRes uptAbnormalTime(@RequestBody AbnormalTimeVO abnormalTimeVO) throws RedisConnectException {
        return systemConfigService.uptAbnormalTime(abnormalTimeVO);
    }

    @ApiOperation(value = "查询离床到异常时间阈值")
    @GetMapping("/abnormalTime")
    public CommonRes getAbnormalTime() {
        return systemConfigService.getAbnormalTime();
    }


    @ApiOperation(value = "删除监测仪")
    @DeleteMapping("/{id}")
    public CommonRes delRadar(@PathVariable Integer id) {
        return radarService.delRadar(id);
    }

    @ApiOperation(value = "超级管理员 分页查询监测仪")
    @GetMapping("/page4tenant/{tenantId}")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前页码，从1开始，默认是1", paramType = "query", dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页条数，默认20", paramType = "query", dataType = "Integer")
    })
    public CommonRes<RadarBedPageVO> pageRadar4Tenant(RadarSearchParam param, @PathVariable @NotNull Integer tenantId) {
        TenantContextHolder.setTenantId(tenantId);
        RadarBedPageVO radarBedPageVO = radarService.showPageRadar(param);
//        if (radarBedPageVO != null && radarBedPageVO.getRadarShowVOIPage() != null
//                && CollectionUtils.isNotEmpty(radarBedPageVO.getRadarShowVOIPage().getRecords())) {
//            List<RadarShowVO> records = radarBedPageVO.getRadarShowVOIPage().getRecords();
//            for (RadarShowVO record : records) {
//                if (record.getBedId() != null) {
//                    record.setBedName(record.getBuildingName()+"-"+record.getFloorName()+"-"+record.getRoomName()+"-"+record.getBedName());
//                }
//            }
//        }
        return CommonRes.ok(radarBedPageVO);
    }


    @ApiOperation(value = "查询跌倒设备属性树形结构")
    @GetMapping("/getFallDownTree")
    public CommonRes<Tree<Bed>> getFallDownTree() {
        Tree<Bed> fallDownTree = radarService.getFallDownTree();
        return CommonRes.ok(fallDownTree);
    }

    @ApiOperation(value = "设置跌倒设备属性")
    @PostMapping("/setFallDownAttr")
    public CommonRes<Object> setFallDownAttr(@RequestBody @Validated FallDownAttrParm fallDownAttrParm) {
        if(StringUtils.isEmpty(fallDownAttrParm.getSn())){
            return CommonRes.failed("sn不能为空");
        }
        return radarService.setFallDownAttr(fallDownAttrParm);
    }

    @ApiOperation(value = "查询跌倒设备属性")
    @GetMapping("/selectFallDownAttr")
    public CommonRes<FallDownAttrVo> selectFallDownAttr(FallDownAttrParm fallDownAttrParm) {
        if(StringUtils.isEmpty(fallDownAttrParm.getSn())){
            return CommonRes.failed("sn不能为空");
        }
        return radarService.selectFallDownAttr(fallDownAttrParm.getSn());
    }

    @ApiOperation(value = "批量设置跌倒设备属性")
    @PostMapping("/batchSetFallDownAttr")
    public CommonRes<Object> batchSetFallDownAttr(@RequestBody @Validated FallDownAttrParm fallDownAttrParm) {
        if(CollectionUtils.isEmpty(fallDownAttrParm.getSnList())){
            return CommonRes.failed("sn不能为空");
        }
        return radarService.batchSetFallDownAttr(fallDownAttrParm);
    }

    @ApiOperation(value = "根据ID查询批量跌倒设备属性")
    @GetMapping("/selecBatchtFallDownAttr")
    public CommonRes<GetBatchFallAttrVo> selecBatchtFallDownAttr(@RequestParam(value="requestId") String requestId) {
        if(StringUtils.isEmpty(requestId)){
            return CommonRes.failed("请求id不能为空");
        }
        return radarService.selecBatchtFallDownAttr(requestId);
    }

    @ApiOperation(value = "更新产品Key")
    @GetMapping("/updateProductKey")
    public CommonRes<Object> updateProductKey() {
        radarService.updateProductKey();
        return CommonRes.ok();
    }


    @ApiOperation(value = "Web获取实时数据")
    @GetMapping("/getWebRealTimeDataV7")
    public CommonRes<RealTimeDataVOV7> getMiniRealTimeDataV7(@NotNull(message = "{required}") String sn,Integer second) {
        Integer tenantId = RecoupUtil.getCurrentUser().getTenantId();
        return hmpDeviceService.getWebRealTimeDataV7(sn, second, tenantId);
    }


}
